package app.keter.portal.exp;

import app.keter.portal.base.BaseController;
import com.keter.framework.web.result.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 验证框架的基础功能和一些实验性功能特性的方法
 */
@Controller
@RequestMapping("/public/exp")
public class ExpController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ExpController.class);

    @GetMapping(value = "/empty")
    @ResponseBody
    public JSONResult emptyDataArray() {
        JSONResult codelist = restTemplate.getForObject(services.getCommon() + "/api/v1/codelist/kind/haha", JSONResult.class);
        if (codelist.isEmpty()) {
            logger.info("没有数据！");
        }
        logger.info("codelist:{}", codelist);
        return codelist;
    }

    /**
     * COMMON 服务专用的RestTemplate
     */
    @Qualifier("commonTemplate")
    @Autowired
    private RestTemplate commonTemplate;

    @ResponseBody
    @GetMapping(value = "/timeout/common")
    public String timeout() {
        logger.info("使用框架定制的CommonTemplate调用超时服务。。。");
        return commonTemplate.getForObject(services.getCommon() + "/exp/timeout", String.class);
    }

    @ResponseBody
    @GetMapping(value = "/timeout/default")
    public String defaultTimeout() {
        RestTemplate simpleTemplate = new RestTemplate();
        AtomicInteger count1 = new AtomicInteger();
        logger.info("使用默认RestTemplate调用超时服务，{}", count1.getAndIncrement() + 1);
        //默认超时在120秒以上
        return simpleTemplate.getForObject("http://127.0.0.1:9990/exp/timeout", String.class);
    }

    @ResponseBody
    @GetMapping(value = "/isolate")
    public boolean isolate() {
//        generateSid();
        logger.info("COMMON服务客户端，objectId={}", commonTemplate.hashCode());
        commonTemplate.getForObject(services.getCommon() + "/api/v1/users/1", JSONResult.class).ensure();
        logger.info("全局客户端，objectId={}", restTemplate.hashCode());
        restTemplate.getForObject(services.getCommon() + "/api/v1/users/1", JSONResult.class).ensure();
        return commonTemplate.hashCode() != restTemplate.hashCode();
    }
}
